package com.bw.module_service.ui.polling

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil.setContentView
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bw.lib_common.arouter.Router
import com.bw.lib_common.base.BaseActivity
import com.bw.module_service.R
import com.bw.module_service.adapter.PhotoAdapter
import com.bw.module_service.databinding.ActivityAddPollingBinding
import com.bw.module_service.model.PhotoItem
import com.bw.module_service.viewmodel.ServiceViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
@Route(path = Router.Ui.AddPollingActivity)
class AddPollingActivity : BaseActivity<ServiceViewModel, ActivityAddPollingBinding>(),
    PhotoAdapter.OnAddPhotoClickListener,
    PhotoAdapter.OnPhotoClickListener {
    override val mLayoutResId: Int
        get() = R.layout.activity_add_polling
    private val mViewModel: ServiceViewModel by viewModels()
    private val itemList = mutableListOf<PhotoItem>()
    private lateinit var photoAdapter: PhotoAdapter
    private val REQUEST_READ_STORAGE_PERMISSION = 100
    private val PICK_IMAGE_REQUEST = 1
    private lateinit var takePhotoTextView: TextView
    private lateinit var choosePhotoTextView: TextView
    private lateinit var bottomSheetDialog: BottomSheetDialog

    override fun initListener() {

    }

    override fun initData() {
        mBinding.addPolling.setOnClickListener {
            val map = mutableMapOf<String, Any>()
            map["projectId"] = mBinding.projectEd.text.toString()
            map["patrolType"] = mBinding.type.text.toString()
            map["pointName"] = mBinding.name.text.toString()
            map["pointLocation"] = mBinding.ip.text.toString()
            map["patrolStandard"] = mBinding.standard.text.toString()
            val json = Gson().toJson(map)
            val body = RequestBody.create("application/json".toMediaTypeOrNull(), json)
            mViewModel.addPolling(body)
            //Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show()
        }
        mBinding.back.setOnClickListener {
            finish()
        }

        mViewModel.addPollingLiveData_.observe(this) {
            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    override fun initView() {
        itemList.add(PhotoItem.AddPhoto)
        photoAdapter = PhotoAdapter(itemList, this, this)
        mBinding.photoRecycler.layoutManager = GridLayoutManager(this, 3)
        mBinding.photoRecycler.adapter = photoAdapter
        bottomSheetDialog = BottomSheetDialog(this)
        bottomSheetDialog.setContentView(R.layout.bottom_sheet_layout)
        takePhotoTextView = bottomSheetDialog.findViewById<TextView>(R.id.tv_take_photo)!!
        choosePhotoTextView = bottomSheetDialog.findViewById<TextView>(R.id.tv_choose_photo)!!

    }

    override fun onAddPhotoClick() {
        takePhotoTextView?.setOnClickListener {
            bottomSheetDialog.dismiss()
            val intent = Intent(this, CameraxActivity::class.java)
            startActivity(intent)
        }
        choosePhotoTextView?.setOnClickListener {
            bottomSheetDialog.dismiss()
            // 检查应用是否已经被授予读取外部存储的权限
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                // 权限已授予，直接打开相册
                openImagePicker()
            } else {
                // 权限未授予，显示权限请求弹窗
                showPermissionExplanationDialog()
            }
        }
        bottomSheetDialog.show()
    }

    //弹窗是否同意权限
    private fun showPermissionExplanationDialog() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("权限请求")
        builder.setMessage("我们需要读取存储权限来加载和处理您的图片，请您允许。")
        builder.setPositiveButton("同意", DialogInterface.OnClickListener { dialog, which ->
            // 用户点击同意后，请求权限
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                REQUEST_READ_STORAGE_PERMISSION
            )
            openImagePicker()
        })
        builder.setNegativeButton("拒绝", DialogInterface.OnClickListener { dialog, which ->
            dialog.dismiss()
        })
        val dialog = builder.create()
        dialog.show()
    }

    private fun openImagePicker() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*"
        startActivityForResult(intent, PICK_IMAGE_REQUEST)
    }

    override fun onPhotoClick(position: Int, photoItem: PhotoItem.Photo) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null) {
            val selectedImageUri = data.data
            // 在这里处理选中的图片，比如显示在 ImageView 上或进行上传等操作
            photoAdapter.addPhoto(selectedImageUri.toString())

        }
    }

}